'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  try {
    const { name, birthYear, mobile, email, address, intro, loginAccount, loginPwd } = event;

    console.log('收到注册请求数据：', { 
      name, birthYear, mobile, loginAccount,
      email: email || '未填',
      address: address || '未填',
      intro: intro || '未填'
    });

    if (!name || !birthYear || !mobile || !loginAccount || !loginPwd) {
      console.log('校验失败：必填项为空');
      return { code: 400, msg: '请填写完整信息' };
    }

    console.log('开始检查用户是否已注册...');
    const dbCmd = db.command;
    const [userByMobile, accountByLogin] = await Promise.all([
      db.collection('UserInfo').where({ mobile }).count(),
      db.collection('Accounts').where({ account: loginAccount }).count()
    ]);

    console.log('检查结果：', {
      userByMobile: userByLogin.total,
      accountByLogin: accountByLogin.total
    });

    if (userByMobile.total > 0) {
      return { code: 400, msg: '该手机号已注册' };
    }
    if (accountByLogin.total > 0) {
      return { code: 400, msg: '该登录账户名已被使用' };
    }

    console.log('开始插入UserInfo...');
    const currentTime = new Date();
    const userData = {
      name,
      birth_year: birthYear,
      mobile,
      email: email || '',
      address: address || '',
      intro: intro || '',
      create_time: currentTime
    };
    
    console.log('UserInfo数据：', userData);
    
    const userAddRes = await db.collection('UserInfo').add(userData);
    console.log('UserInfo插入成功，ID：', userAddRes.id);

    console.log('开始加密密码...');
    const encryptedPwd = Buffer.from(loginPwd).toString('base64');
    console.log('密码加密结果：', { 
      明文: loginPwd, 
      密文: encryptedPwd,
      解密测试: Buffer.from(encryptedPwd, 'base64').toString()
    });

   
    console.log('开始插入Accounts...');
    const accountData = {
      user_id: userAddRes.id,
      account: loginAccount,
      password: encryptedPwd, 
      register_time: currentTime,
      last_login_time: null
    };
    
    console.log('Accounts数据：', accountData);
    
    const accountAddRes = await db.collection('Accounts').add(accountData);
    console.log('Accounts插入成功，ID：', accountAddRes.id);

    console.log('注册流程全部完成');
    return { code: 200, msg: '注册成功' };

  } catch (error) {
    console.error('注册失败：', error);
    console.error('错误堆栈：', error.stack);
    return { code: 500, msg: '注册失败：' + error.message };
  }
};